package hamaster.jpbc.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;

/**
 * HTTP请求发送器
 * @author <a href="mailto:wangyeee@gmail.com">Wang Ye</a>
 */
public class HTTPEngine {

	private static HTTPEngine singleton;

	static {
		if (singleton == null)
			singleton = new HTTPEngine();
	}

	private HTTPEngine() {
	}

	public static HTTPEngine instance() {
		return singleton;
	}

	/**
	 * 通过POST方式发送数据
	 * @param url 接收数据的URL
	 * @param requestProperties 请求附加属性 可以为空
	 * @param data 要发送到数据 多个以&符号分割
	 * @param handler 处理HTTP回应
	 * @throws IOException 发生IO异常
	 */
	public void post(URL url, Properties requestProperties, String data, HTTPResponseHandler handler) throws IOException {
		post(url, requestProperties, data.getBytes(), handler);
	}

	/**
	 * 通过POST方式发送数据
	 * @param url 接收数据的URL
	 * @param requestProperties 请求附加属性 可以为空
	 * @param data 要发送到数据 多个以&符号分割
	 * @param handler 处理HTTP回应
	 * @throws IOException 发生IO异常
	 */
	public void post(URL url, Properties requestProperties, byte[] data, HTTPResponseHandler handler) throws IOException {
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod("POST");
		conn.setConnectTimeout(50000);
		conn.setReadTimeout(50000);
		if (requestProperties != null) {
			for (Object key : requestProperties.keySet()) {
				conn.setRequestProperty((String) key, requestProperties.getProperty((String) key));
			}
		}
		conn.connect();

		OutputStream out = conn.getOutputStream();
		out.write(data);
		out.flush();
		out.close();

		if (handler != null)
			handler.handleHTTPResponse(conn);
		else
			conn.disconnect();
	}

	public static void main(String[] args) {
		HTTPEngine engine = HTTPEngine.instance();
		try {
			URL url = new URL("http://localhost:8080/requesttest/req");
			engine.post(url, null, "a=f&b=g".getBytes(), new HTTPResponseHandler() {
				@Override
				public void handleHTTPResponse(HttpURLConnection conn) {
					final HttpURLConnection conn0 = conn;
					Thread t = new Thread() {
						@Override
						public void run() {
							try {
								BufferedReader in = new BufferedReader(new InputStreamReader((InputStream) conn0.getInputStream()));
								String line = null;
								System.out.println("response:");
								while ((line = in.readLine()) != null) {
									System.out.println(line);
								}
								in.close();
							    conn0.disconnect();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					};
					t.start();
				}
			});
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

